package com.personal.ifanya.presentation.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
 






import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.personal.ifanya.application.dto.NewsDTO;
import com.personal.ifanya.application.service.NewsService;
import com.personal.ifanya.infrastructure.util.VerifyCodeService;
import com.personal.ifanya.presentation.model.AsynResult;
import com.personal.ifanya.presentation.model.SessionBox;


@Controller
@RequestMapping("/news")
@SessionAttributes(value={"sessionBox"})
public class NewsController {

	@Autowired 
	private NewsService newsService;
	 
	@RequestMapping(value="/getnews" ,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getnews(@ModelAttribute("sessionBox") SessionBox sessionBox, 
			@RequestParam("type") int type,
			HttpServletResponse response)
	{  
		AsynResult<List<NewsDTO>> result = new AsynResult<List<NewsDTO>>();
		 
		List<NewsDTO> resultList= newsService.getNewsList(type); 
		result.setAll(true, resultList,  AsynResult.Error.NONE);

		return JSON.toJSONString(result);
	}
	
	@RequestMapping(value="/getlatest",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getlatest(@ModelAttribute("sessionBox") SessionBox sessionBox, 
			HttpServletResponse response)
	{  
		AsynResult<List<NewsDTO>> result = new AsynResult<List<NewsDTO>>(); 
		List<NewsDTO> resultDTO= newsService.getLatestNews(); 
		result.setAll(true, resultDTO,  AsynResult.Error.NONE);
		return JSON.toJSONString(result);
	}
	
	@RequestMapping(value="/show")
	public String show(@ModelAttribute("sessionBox") SessionBox sessionBox, 
			@RequestParam("sourceId") int sourceId,
			Model model,
			HttpServletResponse response)
	{  
		  NewsDTO itemDTO = newsService.getByItemId(sourceId);
		  if(itemDTO!=null)
		  {
			  model.addAttribute("source", itemDTO);
			  if(itemDTO.getSourcelink()!=null && !itemDTO.getSourcelink().isEmpty())
			  { 
				  model.addAttribute("filename", getFilename(itemDTO.getSourcelink()));
			  } 
			  return "detail";
		  }
		  else
		  {
			  return "redirect:/index.html";
		  }
		
	}
	
	@RequestMapping(value="/showadd",produces = "text/html; charset=utf-8")
	public String showadd(@ModelAttribute("sessionBox") SessionBox sessionBox,  @RequestParam(value="message", required=false) String message,Model model,
			HttpServletResponse response) throws UnsupportedEncodingException
	{  
		if(sessionBox.isLogined())
		{
			if(message!=null && !message.isEmpty())
			{
				message = new String(message.getBytes("iso-8859-1"),"UTF-8");
				model.addAttribute("message",message);
			}
			return "add";
		} 
		else
			return "redirect:/login.html";
				
	}
	
	
	@RequestMapping(value="/addnews", method = RequestMethod.POST)
	public String addnews(@ModelAttribute("sessionBox") SessionBox sessionBox, 
			@RequestParam("title") String title, 
			@RequestParam("comment") String comment, 
			@RequestParam("content") String content, 
			@RequestParam(value="file",required = false) MultipartFile file, 
			@RequestParam("type") int type,
			@RequestParam("weight") int weight,
			@RequestParam("how") String how,
			@RequestParam("issueDate") String issueDate,
			Model model,
			HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException
	{  
		 
		if(sessionBox.isLogined())
		{
			NewsDTO dto = new NewsDTO();
			dto.setComment(comment);
			if(content== null || content.isEmpty())
				content = "下载后查看。"; 
			dto.setContent(content);
			
			dto.setHow(how);
			dto.setIssueDate(issueDate);
			dto.setWeight(weight);
			if(file!=null && !file.isEmpty())
			{
				//save file 
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\"  
	                    + file.getOriginalFilename();  
				
				String  sourcelink = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/upload/"+file.getOriginalFilename(); 
				
	            // 转存文件  
	            file.transferTo(new File(filePath));   
				dto.setSourcelink(sourcelink);
			} 
			dto.setTitle(title);
			dto.setType(type);
			if(newsService.insert(dto) )
			{ 
				model.addAttribute("message", "<font color=\"green\">添加成功</font>"); 
			}
			else
			{
				model.addAttribute("message", "<font color=\"red\">添加失败</font>");
			}  
			return "redirect:/news/showadd";
		}
		else
		{
			return "redirect:/login.html";
		} 
	}
	
	
	public static String getFilename(String filename)
	{
		  int i = filename.length() -1;
		  for(; i>=0; i--)
		  {
			  if(filename.charAt(i)=='/')
			  {
				  break;
			  }
		  }
		 return filename.substring(i+1);
	}
	

}
